package ct.zxd.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ct.zxd.bean.Comment;
import ct.zxd.db.TCommentDao;
import net.sf.json.JSONArray;

public class HandleComment extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8;");
		TCommentDao tc = new TCommentDao() ;
		PrintWriter pw = response.getWriter();
		int count = 0;
		
		List<Comment> list = new ArrayList<Comment>() ;
		
		String flag = request.getParameter("flag") ;
		
		Integer id = (request.getParameter("id")) == null ? 0 : Integer.parseInt(request.getParameter("id")) ;
		Integer dishid = (request.getParameter("dishid") == null ? 0 : Integer.parseInt(request.getParameter("dishid"))) ; //���ݿ���int
		String userid = request.getParameter("userid") ;
		String content = request.getParameter("content") ;
		String reply = request.getParameter("reply") ;
		Float score  = (request.getParameter("score") == null ? 0 : Float.parseFloat(request.getParameter("score"))) ;	
		
		try {
			if("add".equals(flag)){			
					
					if(tc.insertComment(dishid , userid , content , score) > 0) {
						count = tc.updateDishComment(score , dishid) ;
					}
					//代表评论成功，同时表示用户不能在评论了
					pw.print((count > 0 ? "评论成功"  : "评论失败"));
			}else if("reply".equals(flag)){
					
					count =  tc.insertCommentReply(id , reply);
					pw.print(count > 0 ? "回复成功"  : "回复失败");
			}else if("all".equals(flag)){
					
					list = tc.selectCommentsByDishid(dishid) ;
//					System.out.println(list);
					JSONArray array = JSONArray.fromObject(list);
//					System.out.println(array);
					pw.print(array);				
			}	
		} catch (SQLException e) {
			e.printStackTrace();
		}	
	}
	
}
